package com.code.util;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.File;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;

public class HelloFreeMarker {

    private Configuration cfg;

    public void init() throws Exception {
        //初始化FreeMarker配置
        //创建一个Configuration实例
        cfg = new Configuration(Configuration.getVersion());
        ;
        //设置FreeMarker的模版文件位置
        String comPath = HelloFreeMarker.class.getClassLoader().getResource("./").getPath();// 获取当前路径下类的编译路径
        System.out.println("com_path:"+comPath);
        File file = new File(comPath,"template");
        if(!file.exists()){
            file.mkdirs();
        }
        cfg.setDirectoryForTemplateLoading(file);
    }

    public void process() throws Exception {
        Map root = new HashMap();
        root.put("name", "FreeMarker!");
        root.put("msg", "您已经完成了第一个FreeMarker的示例");
        Template t = cfg.getTemplate("test.ftl");
        t.process(root, new OutputStreamWriter(System.out));
    }

    public static void main(String[] args) throws Exception {
        HelloFreeMarker hf = new HelloFreeMarker();
        hf.init();
        hf.process();
    }
}